"use client";

import Image from "next/image";
import { Card, Col, Layout, message, Popover, Row, theme} from 'antd';

import { useState, useEffect, useRef, useCallback, useMemo, ReactNode } from "react";
import ShowDialog from "./showDialog";
import LoginFrom from "./Login/LoginFrom";
import CueWordManage from "./maintenance/CueWordManage";
import { MenuItemProps } from "@/service/general/modal/MenuModal";
import { mainMenu } from "@/service/general/menu";
import { DefaultUserSvg } from "./assets/CustomizeSvg";

import './css/page.css';
import { get, isLoggedIn } from "@/service/axiosManager";
import { LogoutOutlined, SettingOutlined, SolutionOutlined } from "@ant-design/icons";
import { logout } from "@/service/localStorageManager";
import { MainContentProvider, useMainContentContext } from "@/service/general/publicStatic";
import { MainContentView } from "./mainContent";
import { ChatView } from "./chat/ChatView";
import { MenuCode } from "@/service/general/enumType";
import { UtilHelpers } from "@/service/general/utils/utilHelpers";

export default function Home() {
  // const {
  //   token: { colorBgContainer, borderRadiusLG },
  // } = theme.useToken();
  const [loggedIn, setLoggedIn] = useState<boolean>(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [cueWordMaintenance, setCueWordMaintenance] = useState<boolean>(false);
  const [isChat, setIschat] = useState<boolean>(false);
  const [chatModel, setChatModel] = useState<ReactNode>(<></>);

  const [checkMenu, setCheckMenu] = useState<MenuItemProps>(mainMenu[1]);

  const [firmName, setFirmName] = useState<string>('');
  const [menuContent, setMenuContent] = useState<ReactNode>(<></>);
  const [userInfo, setUserInfo] = useState<any>();
  const StorageActiveKey = "activeMainMenu";

  useEffect(() => {
    init();
  }, []);

  const init = () => {
    handleLogin();
    loadUserInfo();
    loadingViewData();
    loadFirmName();
  }

  const handleLogin = () => {
    const login = isLoggedIn();
    setLoggedIn(!login);
  }

  const loadUserInfo = () => {
    if (isLoggedIn()) {
      const user = JSON.parse(localStorage.getItem("userInfo") || "");
      setUserInfo(user);
    }
  }

  const loadingViewData = () => {
    const activeMenu = localStorage.getItem(StorageActiveKey);
    if (activeMenu) {
      setCheckMenu(mainMenu[parseInt(activeMenu)]);
      setMenuContent(mainMenu[parseInt(activeMenu)].content);
      // setFirstHistory();
      // setMainContentView(mainMenu[parseInt(activeMenu)].content);
    }
  }

  const loadFirmName = () => {
    if (firmName) return;
    get("/system/title",{}, false).then((res) => {
      let result = res.result;;
      if (res.code === 0 && res.success && result) {
        console.log("FirmName: " + result);
        setFirmName(result);
      } else {
        result = res?.message || "加载公司名称失败，服务异常";
          console.error(result);
          message.error(result);
      }
    }).catch((err) => {
      console.log('加载公司名称失败', err);
    });
  }

  const toChatView = () => {
    const medel = <ChatView callback={closeChatView} />
    setChatModel(medel);
    setIschat(true);
  }

  const closeChatView = () => {
    UtilHelpers.CleanTimeout("Process-msg");
    setIschat(false);
    setChatModel(<></>);
  }

  const getMenuContent = (node: ReactNode):ReactNode => {
    return node;
  }

  // const handleButtonClick = (view: string) => {
  //   setActiveView(view);
  // };

  return (
    <>
      
        <Layout style={{ height: '100vh' }}>
          <LoginFrom
            open={loggedIn}
            setOpen={(open: boolean) => {
              console.log('open', open);
            }}
            firmName={firmName}
          />
          {
            isChat ? (
            <>
              <div className="w-full h-full bg-[#F4F4F7]">
                {chatModel}
              </div>
            </>) : (
              <>
                <div className="w-full h-full bg-[#F4F4F7]">
                  <div className="w-full h-full flex flex-row justify-center items-center">
                    <div className="w-fit h-full flex flex-col justify-start items-start">
                      <div className="w-full flex flex-col justify-center items-center gap-1 py-6 px-4">
                        <Popover content={
                          <>
                          <div className="flex flex-col gap-3 items-start justify-start py-4 px-2">
                            <div 
                            className="w-full flex flex-row gap-2 items-center justify-start cursor-pointer rounded-lg px-4 py-2 hover:bg-gray-200 hover:text-blue-500"
                            onClick={() => {setDialogOpen(true);}}
                            >
                              <div className="flex flex-row items-center justify-center w-4"><SettingOutlined /></div>
                              <div>修改密码</div>
                            </div>
                            <div 
                            className="w-full flex flex-row gap-2 items-center justify-start cursor-pointer rounded-lg px-4 py-2 hover:bg-gray-200 hover:text-blue-500"
                            onClick={() => {setCueWordMaintenance(true);}}
                            >
                              <div className="flex flex-row items-center justify-center w-4"><SolutionOutlined  /></div>
                              <div>维护提示词</div>
                            </div>
                            <div 
                            className="w-full flex flex-row gap-2 items-center justify-start cursor-pointer rounded-lg px-4 py-2 hover:bg-gray-200 hover:text-blue-500"
                            onClick={() => {
                              logout();
                            }}
                            >
                              <div className="flex flex-row items-center justify-center w-4"><LogoutOutlined /></div>
                              <div>退出</div>
                            </div>
                          </div>
                          </>
                        } arrow={false} trigger="hover" mouseLeaveDelay={0.5} placement="rightTop" overlayInnerStyle={{ padding: 0,marginLeft: 0 }}>
                          <div className="w-8 h-8 flex justify-center items-center bg-red-500 rounded-full p-2">
                            <div><DefaultUserSvg width={24} height={24} color="#FFFFFF" /></div>
                          </div>
                        </Popover>
                        <div className="flex flex-row items-center justify-center px-3 cursor-pointer rounded-full bg-green-100 text-blue-700">{userInfo?.username}</div>
                      </div>
                      <div className="w-full h-full flex flex-col gap-2 justify-start items-center">
                        {mainMenu.map((itemMenu: MenuItemProps,index) => {
                            return (
                              <div
                                className={`w-12 h-fit cursor-pointer text-xs text-gray-400 border border-transparent rounded-lg flex flex-col  gap-1 justify-center items-center py-2 hover:bg-white`}
                                style={checkMenu.id === itemMenu.id ? {
                                  backgroundColor: "white",
                                  borderWidth: "1px",
                                  color: "#1d4ed8",
                                  boxShadow: "0 0 8px rgba(96, 165, 250, 0.1)",
                                }: {}}
                                key={`menu_item_${itemMenu.id}`}
                                onClick={() => {
                                  if (itemMenu.code === MenuCode.CHAT) {
                                    toChatView();
                                    return;
                                  }
                                  setCheckMenu(itemMenu);
                                  setMenuContent(itemMenu.content);
                                  localStorage.setItem(StorageActiveKey, index.toString());
                                  itemMenu.onClick(itemMenu);
                                }}
                              >
                                <div>{itemMenu.icon}</div>
                                <div>{itemMenu.name}</div>
                              </div>
                            );
                          })
                        }
                      </div>
                    </div>
                    <div className="w-full h-full px-6 py-3">
                      <MainContentProvider>
                        <MainContentView mContent={menuContent} />
                      </MainContentProvider>
                    </div>
                  </div>
                  <div></div>
                </div>
              </>
            )
          }
          
        </Layout>
      <ShowDialog open={dialogOpen} setOpen={setDialogOpen} />
      <CueWordManage open={cueWordMaintenance} setOpen={setCueWordMaintenance}/>
    </>
  );
}
